import json
import time
from flask import Blueprint,request,redirect,make_response,Response
from application.models.model import *
from cache import my_cache
from swaager_init import siwa,BaseModel
from db_init import db
from tools.data_tools import orm2dict,ret_route,limit_framt
from flask_login import login_user,login_required,current_user
from config import VIP_EBD_TIME, LOGIN_APP_MAP, LIMIT, OFFSET, CAR
from functools import reduce

tocourse = siwa.blueprint("tocourse", __name__)

# 获取所有的训练营
@tocourse.route('/get_all',methods=['get'])
def tocourse_list():
    end_id = int(request.args.get('end_id'),0)
    sql = Tcourse.query.filter(Tcourse.online == 1,Tcourse.id.__gt__(end_id)).limit(LIMIT).all()
    return ret_route(200,data=orm2dict(sql))

# 获取训练营的进度
@tocourse.route("/<int:tcourse_id>", methods=['GET'])
def course_info(tcourse_id):
    tocours = Tcourse.query.get(tcourse_id)
    data = orm2dict(tocours)
    course = orm2dict(tocours.course)
    data['course'] = course
    data['teacher'] = orm2dict(tocours.teacher,filter=['password'])
    try:
        user_course = db.session.query(user_tcourse_course)\
        .filter(user_tcourse_course.c.user_id == current_user.id,
                user_tcourse_course.c.tcourse_id == tcourse_id).all()
        data['user_course'] = [i[0] for i in user_course]
    except Exception as e:
        data['user_course'] = []
    return ret_route(data=data)

# 打折
@tocourse.route('/money/<int:tcourse_id>',methods=['post'])
@login_required
def tourse_order(tcourse_id):
    tcourse = Tcourse.query.get(tcourse_id)
    zhe = 1
    for role in current_user.role:
        zhe *= role.zhe

    price = tcourse.price * zhe

    user_bean_price = current_user.bean // 100
    if user_bean_price > price:
        price = 0
        current_user.bean = (user_bean_price - tocourse.price * zhe) * 100 + current_user.bean % 100
    else:
        current_user.bean = current_user.bean % 100
        price -= user_bean_price

    info = {**orm2dict(tcourse,filter=['online']),'price':price}
    my_cache.hmset(f'{CAR}{current_user.id}', {int(time.time()): json.dumps(info)})
    db.session.commit()

    return ret_route(200,data=orm2dict(info))

@tocourse.route('/car',methods=['get'])
@login_required
def get_tourse():
    car_data = my_cache.hgetall(f'{CAR}{current_user.id}')
    return ret_route(200,data=car_data)






